import { NextResponse } from 'next/server'
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'

let locales = ['en', 'zh']
let defaultLocale = 'zh'

// Get the preferred locale from headers
function getLocale(request) {
  const headers = new Headers(request.headers)
  const acceptLanguage = headers.get('accept-language')
  if (!acceptLanguage) return defaultLocale

  const languages = new Negotiator({ headers: { 'accept-language': acceptLanguage } }).languages()
  return match(languages, locales, defaultLocale)
}

export function checkLanguage(request) {
  const pathname = request.nextUrl.pathname
  
  const pathnameIsMissingLocale = locales.every(
    (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
  )

  // Redirect if there is no locale
  if (pathnameIsMissingLocale) {
    const locale = getLocale(request)
    // 重定向时需要加上 basePath
    return NextResponse.redirect(
      new URL(`/ty/${locale}${pathname}`, request.url)
    )
  }
}
